package cn.sc.summer.feign.decoder;

import cn.hutool.core.util.ObjectUtil;
import cn.sc.summer.constant.model.Result;
import cn.sc.summer.exception.exceptions.FeignException;
import cn.sc.summer.token.service.EncryptService;
import com.alibaba.fastjson.JSONObject;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

/**
 * feign 异常处理
 *
 * @author a-xin
 */
@Slf4j
@Configuration
public class FeignErrorDecoder implements ErrorDecoder {

    @Resource
    private EncryptService encryptService;

    /**
     * 自定义错误
     */
    @Override
    public Exception decode(String methodKey, Response response) {
        String[] client = methodKey.split("#");
        String data = "The service is abnormal！";
        Result<?> result;
        try {
            String errorContent = Util.toString(response.body().asReader(StandardCharsets.UTF_8));
            data = StringEscapeUtils.unescapeJava(errorContent);
            result = JSONObject.parseObject(encryptService.decryptFeignData(data), Result.class);
        } catch (Exception e) {
            result = JSONObject.parseObject(data, Result.class);
        }
        log.error("==> An OpenFeign exception is detected: {}, Client: {}, Method: {}, reason: {}", result, client[0], client[1], result.getMessage());
        if (response.status() != HttpStatus.OK.value() && ObjectUtil.isNotNull(result)) {
            return JSONObject.parseObject(JSONObject.toJSONString(result), FeignException.class);
        }
        return new FeignException(result.getMessage());
    }

}
